package tech.aichan.AiQA.utils;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import javax.security.sasl.AuthenticationException;
import java.util.Date;
import java.util.HashMap;
/**
 * @author mengyu
 * @date 2024/02/08 9:33
 */
@Slf4j
public class JwtUtil {

    /**
     * 生成jwt
     * 使用Hs256算法, 私匙使用固定秘钥
     *
     * @return
     */
    public static String createJWT(String secretKey,Long userId, Long ttlMin) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);

        Date expiration = new Date(System.currentTimeMillis() + ttlMin * 60 * 1000);
        return JWT.create()
                .setKey(secretKey.getBytes())
                .setExpiresAt(expiration)   // 设置过期时间
                .addPayloads(map)
                .sign();
    }

    /**
     * Token解密
     * @param token     加密后的token
     * @return
     */
    public static Long parseJWT(String secretKey,String token) {
        long userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            boolean isValid = jwt.setKey(secretKey.getBytes()).validate(0);
            if (isValid) {
                NumberWithFormat number = (NumberWithFormat) jwt.getPayload("userId");
                userId = number.longValue();
            } else {
                throw new AuthenticationException("token非法");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return userId;
    }

}
